package com.adk.backend.config;

import com.adk.backend.entity.LxAdmin;
import com.adk.backend.mapper.AdminMapper;
import com.adk.backend.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT认证过滤器
 * 用于验证Token并将用户信息存储到Request中
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private AdminMapper adminMapper;
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        
        String authHeader = request.getHeader("Authorization");
        String token = null;
        
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7);
            // 验证Token并将用户信息存储到Request属性中
            if (jwtUtil.validateToken(token)) {
                Long userId = jwtUtil.getUserIdFromToken(token);
                String username = jwtUtil.getUsernameFromToken(token);
                if (userId != null && username != null) {
                    request.setAttribute("userId", userId);
                    request.setAttribute("username", username);
                    
                    // 获取用户详细信息（包括用户组和customer_id）
                    try {
                        LxAdmin admin = adminMapper.selectById(userId);
                        if (admin != null) {
                            // 设置用户组（user_type）
                            if (admin.getUserType() != null) {
                                request.setAttribute("userGroup", admin.getUserType());
                            }
                            // 设置客户ID（customer_id）
                            if (admin.getCustomerId() != null) {
                                request.setAttribute("customerId", admin.getCustomerId());
                            }
                        }
                    } catch (Exception e) {
                        // 如果获取用户信息失败，不影响后续流程
                    }
                }
            }
        }
        
        chain.doFilter(request, response);
    }
}

